package com.example.xmlparsedemo

import android.content.Context
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.InputStream

class PullHelper {
    companion object {
        fun getList(context: Context): MutableList<WxAccountBean>? {
            var inputStream = context.assets.open("demo.xml")
            var list: MutableList<WxAccountBean>? = null
            var wxAccountBean: WxAccountBean? = null
            //获取工厂类
            var xmlPullParserFactory = XmlPullParserFactory.newInstance()
            //获取解析类
            var xmlPullParser = xmlPullParserFactory.newPullParser()
            xmlPullParser.setInput(inputStream, "utf-8")
            //获取事件类型

            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                when (eventType) {
                    //开始读取文档
                    XmlPullParser.START_DOCUMENT -> {
                        list = arrayListOf()
                    }
                    //开始读取标签
                    XmlPullParser.START_TAG -> {
                        when (xmlPullParser.name) {
                            "WxAccount" -> {
                                wxAccountBean = WxAccountBean()
                            }
                            "name" -> {
                                wxAccountBean?.name = xmlPullParser.nextText()
                            }
                            "sex" -> {
                                wxAccountBean?.sex = xmlPullParser.nextText()
                            }
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        when (xmlPullParser.name) {
                            "WxAccount" -> {
                                list?.add(wxAccountBean!!)
                                wxAccountBean = null
                            }
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
            return list
        }
    }
}